import React, { useState, useCallback } from 'react';
import { Button } from 'antd';
import { useEffect } from 'react';


const set = new Set();
/**
 * 应用场景：考虑到性能优化，在更新苹果count状态值时，不渲染子页面呢？
 * 解决方案：使用useCallback
 */
export default () => {
    const [miCount, setMiCount] = useState(0);
    const [appleCount, setAppleCount] = useState(0);

    /**
     * @description 计算小米手机当前销售额
     * 这里用useCallback包裹要处理的函数，用法和useEffect类似，会在页面渲染之前执行一次，
     * 相当于componentWillMount生命周期函数，如何miCount发生变化也相当于有componentWillUpdate
     * useCallback的返回是缓存的函数，即handleCalc仍然是函数
     */
    const handleCalc = useCallback(() => {
        console.log('----进入复杂逻辑----');
        // 真实案例中，会有复杂的计算逻辑，会特别消耗性能
        return miCount * 3980;
    }, [miCount]);

    set.add(handleCalc);

    return (
        <>
            {console.log('----父组件页面渲染----')}
            <div>
                {set.size}
                <Child callback={handleCalc} />
            </div>
            <div>
                <span style={{ marginRight: 6 }}>
                    {`小米手机当前售出：${miCount} 台`}
                </span>
                <span>
                    <Button onClick={() => setMiCount(miCount + 1)}>+1</Button>
                </span>
            </div>
            <div>
                <span style={{ marginRight: 6 }}>
                    {`苹果手机当前售出：${appleCount} 台`}
                </span>
                <span>
                    <Button onClick={() => setAppleCount(appleCount + 1)}>+1</Button>
                </span>
            </div>
        </>
    )
}

const Child = ({ callback }) => {
    // const { callback } = props;
    const [applePrice, setApplePrice] = useState(() => callback())
    useEffect(() => {
        setApplePrice(callback());
    }, [callback]);
    console.log(22)
    return (
        <div>
            {console.log('----子组件渲染----')}
            {`小米手机当前销售额：${applePrice} 元`}
        </div>
    )
}
